import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart' hide Response, FormData, MultipartFile;
import 'package:get/get_core/src/get_main.dart';

import '../env.dart';
import 'api.dart';

class Http {
  static String authorization =
      'Basic ${base64.encode(utf8.encode('saber:saber_secret'))}';
  static Http instance = Http._();

  // static const String baseUrl = 'http://10.86.130.21:31186'; //dev
  // static const String baseUrl = 'http://10.86.130.31:32732'; //sit

  Http._() {
    _init();
  }

  late Dio _dio;

  _init() {
    _dio = Dio()
      ..options = BaseOptions(
        connectTimeout: const Duration(seconds: 60),
        receiveTimeout: const Duration(seconds: 120),
        baseUrl: BuildEnvironment.instance.baseUrl,
      );
    //网络代理
    if (kDebugMode) {
      // _addProxy(_dio);
    }
    _dio.interceptors.add(BusinessInterceptor()); //业务请求拦截
    _dio.interceptors.add(LogInterceptor());
  }

  String proxyPort() {
    return "9090"; //代理软件的端口
  }

  String proxyHost() {
    return '192.168.16.79'; //改成你的电脑ip就可以代理到你的电脑上了
  }

  ///设置代理
  void _addProxy(Dio instance) {
    if (proxyHost().isNotEmpty && proxyPort().isNotEmpty) {
      (instance.httpClientAdapter as IOHttpClientAdapter).createHttpClient =
          () {
        final client = HttpClient();
        client.findProxy = (uri) {
          return "PROXY ${proxyHost()}:${proxyPort()}";
        };
        client.badCertificateCallback =
            (X509Certificate cert, String host, int port) => true;
        return client;
      };
    }
  }

  Future<Response> httpGet(String path,
      {Map<String, dynamic>? queryParam, Options? options}) async {
    return _dio.get(path, queryParameters: queryParam, options: options);
  }

  Future<Response> httpPost(String path,
      {Map<String, dynamic>? queryParam,
        dynamic data,
        Options? options}) async {
    return _dio.post(path,
        queryParameters: queryParam, data: data, options: options);
  }

  Future<Response> httpPut(String path,
      {Map<String, dynamic>? queryParam,
        dynamic data,
        Options? options}) async {
    return _dio.put(path,
        queryParameters: queryParam, data: data, options: options);
  }


}

class BusinessInterceptor extends Interceptor {
  String? dataCenterUUid;

  @override
  void onRequest(
      RequestOptions options, RequestInterceptorHandler handler) async {
    options.headers.putIfAbsent('Tenant-Id', () => '000000');

    if (![Api.captcha].contains(options.path)) {
      options.headers.putIfAbsent('authorization', () => Http.authorization);

      if (![Api.login].contains(options.path)) {
        options.headers.putIfAbsent(
            "blade-auth", () => 'bearer accessToken');
      }
    }
    super.onRequest(options, handler);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    if (err.response?.statusCode == 401) {
      SmartDialog.showToast('登录信息已过期, 请重新登录'.tr);
      Get.offAllNamed("/login");
    }
    super.onError(err, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    if (response.statusCode == 200) {
      if (response.data is String) {
        try {
          response.data = jsonDecode(response.data);
        } catch (e) {
          print('response.data parse failed');
        }
      }
      if (response.data['code'] == null) {
        handler.next(response);
      } else if (response.data['code'] == 200) {
        response.data = response.data['data'];
        handler.resolve(response);
      } else {
        handler.reject(DioException(
          requestOptions: response.requestOptions,
          message: response.data['msg'],
        ));
      }
    } else {
      handler.reject(DioException(
        requestOptions: response.requestOptions,
        message: response.statusMessage,
      ));
    }
  }
}
